package utils

import (
	"fmt"
	"gopkg.in/ini.v1"
	"time"
)

type Server struct {
	RunMode      string
	HttpPort     string
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

var ServerSetting = &Server{}

type Database struct {
	Type        string
	Local		string
	DBMaxOpen	int
	DBMaxIdle	int
}

var DatabaseSetting = &Database{}

type Redis struct {
	Host        string
	Password    string
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
}

var RedisSetting = &Redis{}

type Jwt struct {
	Secret      string
	Timeout     int64
}

var JwtSetting = &Jwt{}

type Log struct {
	FilePath      string
	LinkName      string
}

var LogSetting = &Log{}


var cfg *ini.File

func InitCof() (err error) {
	cfg, err = ini.Load("conf/conf.ini")
	if err != nil {
		fmt.Println("配置文件读取错误,找不到配置文件", err)
		return err
	}

	err = mapTo("server", ServerSetting)
	if err != nil {
		return
	}
	err = mapTo("database", DatabaseSetting)
	if err != nil {
		return
	}
	err = mapTo("redis", RedisSetting)
	if err != nil {
		return
	}
	err = mapTo("jwt", JwtSetting)
	if err != nil {
		return
	}
	err = mapTo("logger", LogSetting)
	if err != nil {
		return
	}

	ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second
	ServerSetting.WriteTimeout = ServerSetting.WriteTimeout * time.Second
	RedisSetting.IdleTimeout = RedisSetting.IdleTimeout * time.Second

	return
}

// mapTo map section
func mapTo(section string, v interface{}) (err error) {
	err = cfg.Section(section).MapTo(v)
	if err != nil {
		fmt.Printf("Cfg.MapTo %s err: %v", section, err)
	}
	return
}